package leetcode.f1t100;

/**
 * 给一个数字n, 返回1~n组成的搜索二叉树有多少种
 * https://leetcode.com/problems/unique-binary-search-trees/
 *
 * @author lichx
 * @createTime 2024/2/21 14:04
 */
public class Q96_UniqueBinarySearchTrees {
    public static void main(String[] args) {
        Q96_UniqueBinarySearchTrees bean = new Q96_UniqueBinarySearchTrees();
        System.out.println(bean.numTrees(5));
    }

    public int numTrees(int n) {
        int[][] dp = new int[n + 1][n + 1];
        for (int i = 0; i <= n; i++) {
            for (int j = 0; j <= n; j++) {
                if (i >= j) {
                    dp[i][j] = 1;
                }
            }
        }
        for (int j = 2; j <= n; j++) {
            for (int i = j - 1; i >= 1; i--) {
                int count = 0;
                for (int k = i; k <= j; k++) {
                    int left = 1;
                    if (i < k - 1) {
                        left = dp[i][k - 1];
                    }
                    int right = 1;
                    if (k + 1 < j ) {
                        right = dp[k + 1][j];
                    }
                    count += left * right;
                }
                dp[i][j] = count;
            }
        }
        return dp[1][n];
    }
}
